package com.acc.store.interceptor;


import com.acc.store.entity.User;
import com.acc.store.utils.JWTUtils;
import com.aliyun.oss.common.utils.StringUtils;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("进入拦截器");
        if (!(handler instanceof HandlerMethod)) {
            log.debug("不是动态方法");
            return true;
        }
        String token = request.getHeader("token");
        try {
            log.debug("jwt校验:{}", token);
            if (StringUtils.isNullOrEmpty(token)) {
                log.debug("令牌为空");
                return false;
            }
            JWTUtils jwtUtils = new JWTUtils();
            Claims claims = jwtUtils.parseToken(token);
            log.debug("校验令牌值{}", claims.toString());
            String key = (String) claims.get("sub");
            User byId = Db.getById(key, User.class);
            if(byId==null){
                log.debug("未知错误");
                response.setStatus(401);
                return false;
            }
            if (byId.getPermissionLevel()==1) {
                log.debug("管理员操作");
            } else {
                log.debug("店员{}操作", key);
            }
            return true;
        } catch (Exception ex) {
            log.debug("校验失败:{}", ex.toString());
            response.setStatus(401);
            return false;
        }
    }
}